package com.github.browep.bat.util;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: paul
 * Date: 8/26/11
 * Time: 4:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class XmlUtil {

    public static Element getElementByTagName(Element element, String tagName){
        NodeList nodeList = element.getElementsByTagName(tagName);
        if(nodeList.getLength() > 1){
            throw new IllegalArgumentException(element.toString() + " has more than one " + tagName + " tag");
        }else if(nodeList.getLength() == 0){
            return null;
        }
        return (Element) nodeList.item(0);
    }

    public static Element getElementByTagAndId(Element parent, String tagName, String id){
        if(id == null)
            throw new IllegalArgumentException("id cannot be null");
        NodeList nodeList = parent.getElementsByTagName(tagName);
        for(int i=0;i<nodeList.getLength();i++){
            Node node = nodeList.item(i);
            if(node instanceof Element && id.equals(((Element) node).getAttribute("id")))
                return  (Element)node;
        }

        return null;

    }

    public static List<Element> getChildElementListWithTag(Element parent, String tagName){
        NodeList nodeList = parent.getElementsByTagName(tagName);
        List<Element> elements = new LinkedList<Element>();
        for(int i = 0; i<nodeList.getLength(); i++){
            Node node = nodeList.item(i);
            if(node instanceof Element)
                elements.add((Element) node);
        }
        return elements;

    }

    public static String getChildTextContent(Element element, String tagName){
        return  getElementByTagName(element,tagName).getTextContent().trim();
    }

    public static boolean hasChildElement(Element element, String tagName){
        return !getChildElementListWithTag(element, tagName).isEmpty();
    }


}
